package com.jyh.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jyh.common.R;
import com.jyh.dto.DishDto;
import com.jyh.pojo.Category;
import com.jyh.pojo.Dish;
import com.jyh.pojo.DishFlavor;
import com.jyh.service.CategoryService;
import com.jyh.service.DishFlavorService;
import com.jyh.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RequestMapping("/dish")
@RestController
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 添加菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> addDish(@RequestBody DishDto dishDto){

        dishService.saveDishAndFlavor(dishDto);
        //清理redis对应的缓存
        String key="dish_"+dishDto.getCategoryId();
        redisTemplate.delete(key);

        return R.success("success");
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name){
        //log.info("page:{},pageSize:{}",page,pageSize);

        Page<Dish> dishPage=new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage=new Page<>();

        LambdaQueryWrapper<Dish> lqw=new LambdaQueryWrapper<>();
        //name不为空，按菜品名称升序、更新时间降序排列
        lqw.like(name!=null,Dish::getName,name).orderByAsc(Dish::getCategoryId).orderByDesc(Dish::getUpdateTime);

        dishService.page(dishPage,lqw);
        //dishPage是有值的，将其复制到dtoPage里面
        BeanUtils.copyProperties(dishPage,dishDtoPage,"records");
        //获取查询到的分页数据
        List<Dish> records = dishPage.getRecords();
        List<DishDto> list=new ArrayList<>();

        //遍历分页数据，对每一条数据进行查询
        for(Dish record : records ) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(record,dishDto);
            //获取当前dish的菜品id
            Long categoryId = dishDto.getCategoryId();
            //根据菜品id，查询对应的菜品分类
            Category category = categoryService.getById(categoryId);
            //菜品分类名称
            String categoryName = category.getName();
            //将菜品名称赋值到disDTO中的category属性
            dishDto.setCategoryName(categoryName);

            list.add(dishDto);
        }
        dishDtoPage.setRecords(list);
        //log.info("dishDtoPage:{}",dishDtoPage);
        return R.success(dishDtoPage);
    }

    /**
     * 查询菜品及口味信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> edit(@PathVariable Long id){
        //log.info("id:{}",id);
        DishDto dishDto = dishService.getDishAndFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 编辑菜品信息
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        //log.info("dishDto:{}",dishDto);
        dishService.updateDishAndFlavor(dishDto);

        //清理redis对应的缓存
        String key="dish_"+dishDto.getCategoryId();
        redisTemplate.delete(key);
        return R.success("success");
    }

    /**
     * 批量启用、禁用
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> status(@PathVariable int status, Long[] ids){
        //log.info("状态:{}",status);


        //0:停售，1：起售
        LambdaQueryWrapper<Dish> lqw=new LambdaQueryWrapper<>();

        List<Dish> list=new ArrayList<>();
        for (Long id :ids ) {
            Dish dish = dishService.getById(id);
            dish.setStatus(status);
            list.add(dish);
        }
        dishService.updateBatchById(list);
        return R.success("success");
    }


    /**
     * 删除，批量删除
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids){
        //log.info("ids:{}",ids);
        dishService.deleteDishAndFlavor(ids);
        return R.success("success");
    }

    /**
     * 新增套餐时、主页面，展示菜品信息
     * @param dish
     * @return
     */
//    @GetMapping("/list")
//    public R<List<Dish>> list(Dish dish){
//        //log.info("categoryId:{}",dish.getCategoryId());
//
//        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper=new LambdaQueryWrapper<>();
//        //根据菜品id
//        dishLambdaQueryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
//
//        //排序
//        dishLambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
//
//        //只查起售
//        dishLambdaQueryWrapper.eq(Dish::getStatus,1);
//        List<Dish> dishes = dishService.list(dishLambdaQueryWrapper);
//
//        return R.success(dishes);
//    }
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        //log.info("categoryId:{}",dish.getCategoryId());

        List<DishDto> dishDtoList;
        //加入redis缓存菜品信息，根据菜品分类缓存
        String key="dish_"+dish.getCategoryId();

        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if(dishDtoList!=null){
            //有缓存直接返回
            R.success(dishDtoList);
        }

        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper=new LambdaQueryWrapper<>();
        //根据菜品id
        dishLambdaQueryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        //排序
        dishLambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //只查起售
        dishLambdaQueryWrapper.eq(Dish::getStatus,1);

        List<Dish> dishes = dishService.list(dishLambdaQueryWrapper);

        //遍历dishes数据，对每一条数据设置口味
        dishDtoList=dishes.stream().map((d)->{
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(d,dishDto);

            Long id = d.getId();
            LambdaQueryWrapper<DishFlavor> flavorLambdaQueryWrapper=new LambdaQueryWrapper<>();
            //查每个菜品对应的所有口味信息
            flavorLambdaQueryWrapper.eq(DishFlavor::getDishId,id);
            List<DishFlavor> flavors = dishFlavorService.list(flavorLambdaQueryWrapper);
            dishDto.setFlavors(flavors);
            return dishDto;
        }).collect(Collectors.toList());

        //redis加入缓存
        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);

        return R.success(dishDtoList);
    }

}
